import express, { Application } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import { config } from '@/config';
import { connectDatabase } from '@/config/database';
import { errorHandler } from '@/middleware/errorHandler';
import routes from '@/routes';

const app: Application = express();

// Security middleware
app.use(helmet());
app.use(cors(config.cors));

// Rate limiting
const limiter = rateLimit(config.rateLimit);
app.use(limiter);

// Logging
app.use(morgan('combined'));

// Body parsing middleware
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// Health check endpoint
app.get('/health', (_req, res) => {
  res.json({
    status: 'OK',
    timestamp: new Date().toISOString(),
    environment: config.nodeEnv,
  });
});

// API routes
app.use('/', routes);

// Legacy API root endpoint (for backward compatibility)
app.get('/api', (_req, res) => {
  res.json({
    message: 'Fitness Trainer API',
    version: '1.0.0',
    endpoints: {
      health: '/health',
      auth: '/api/v1/auth',
      members: '/api/v1/members',
      courses: '/api/v1/courses',
      exercises: '/api/v1/exercises',
      trainingPlans: '/api/v1/training-plans',
      trainingRecords: '/api/v1/training-records',
    },
  });
});

// Error handling middleware (must be last)
app.use(errorHandler);

// 404 handler
app.all('*', (_req, res) => {
  res.status(404).json({
    success: false,
    message: 'Route not found',
    timestamp: new Date(),
  });
});

const startServer = async (): Promise<void> => {
  try {
    // Try to connect to database (optional for development)
    try {
      await connectDatabase();
    } catch (dbError: any) {
      console.warn('Database connection failed, continuing without database:', dbError.message);
    }
    
    // Start server
    app.listen(config.port, () => {
      console.log(`Server running on port ${config.port}`);
      console.log(`Environment: ${config.nodeEnv}`);
      console.log(`Health check: http://localhost:${config.port}/health`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
};

// Handle graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('SIGINT received, shutting down gracefully');
  process.exit(0);
});

// Start the server
startServer();

export default app;